package main

import (
    "os"
    "os/signal"
    "syscall"
    "time"

    "github.com/go-echarts/statsview"
    "go.uber.org/zap"
    "iip/account"
    "iip/config"
    "iip/dictionary"
    "iip/idgen"
    "iip/iip"
    "iip/logger"
    "iip/webserver"
    "iip/wx"
    "libgo/database/mysql"
    "libgo/storage/db_config"
    "libgo/storage/oss"
)

func main() {
    go func() {
        mgr := statsview.New()
        mgr.Start()
    }()

    sigs := make(chan os.Signal, 1)
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
    go func() {
        <-sigs
        os.Exit(0)
    }()

    l := logger.New().NewZapLogger("tms").WithOptions(zap.AddCaller())
    log := l.With(zap.String("mod", "main")).Sugar()

    config.WithLogger(l)
    cfg, err := config.NewFromFile("conf/config.ini")
    if err != nil {
        l.Error("加载配置文件失败:" + err.Error())
        return
    }
    l.Info("加载配置文件成功")

    idg := idgen.New().WithNodeID(cfg.IDGen.NodeID)
    if err := idg.Open(); err != nil {
        l.Error(err.Error())
        return
    }

    db_iip, err := mysql.New().WithLogger(l).DSN(cfg.Database.DSN).MaxIdleConns(10).MaxOpenConns(50).MaxConnLifeTime(time.Hour).Gorm()
    if err != nil {
        log.Error("连接数据库失败:" + err.Error())
        return
    } else {

        log.Infof("连接数据库%s成功", mysql.DSNDesensitization(cfg.Database.DSN))
    }
    db_acc, err := mysql.New().WithLogger(l, true).DSN(cfg.DBAccount.DSN).MaxIdleConns(10).MaxOpenConns(50).MaxConnLifeTime(time.Hour).Gorm()
    if err != nil {
        log.Error("连接数据库失败:" + err.Error())
        return
    } else {

        log.Infof("连接数据库%s成功", mysql.DSNDesensitization(cfg.DBAccount.DSN))
    }

    bkt, err := oss.NewMinio().WithLogger(l).WithConfig(&cfg.Minio).OpenBucket("avatar")
    if err != nil {
        log.Error(err)
        return
    }

    websrv := webserver.New().WithLogger(l).WithConfig(&cfg.WebServer)
    websrv.SetupNormal()
    websrv.SetupCORS()
    websrv.SetupJWT()

    app_dbcfg := db_config.New().WithLogger(l).WithDB(db_iip)
    if err := app_dbcfg.Start(); err != nil {
        log.Error("dbcfg failed", err)
    }

    app_dict := dictionary.New().WithLogger(l).WithDB(db_iip).WithDBConfig(app_dbcfg).WithWebServer(websrv).WithIDGen(idg)
    app_dict.Start()
    log.Info("启动dictionary成功")

    app_acc := account.New().WithLogger(l).WithDB(db_acc).WithWebServer(websrv).WithIDGen(idg).WithOSS(bkt).WithDictionary(app_dict)
    app_acc.Start()

    app_iip := iip.New().WithLogger(l).WithConfig(&cfg.TMS).WithDB(db_iip).WithDBConfig(app_dbcfg).WithWebServer(websrv).WithDictionary(app_dict)
    app_iip.Start()
    log.Info("启动iip成功")

    app_wx := wx.New().WithLogger(l).WithConfig(&cfg.WX).WithWebServer(websrv)
    app_wx.Start()
    log.Info("启动wx成功")

    websrv.BStart()
}
